//加载express框架
const express = require('express');
//实例路由
const router = express.Router();
//导入数据模型
const {
  user
} = require('../model/db');

//------------上传配置------------------------------
//导入multer
const multer = require('multer')
//上传参数设置
const storage = multer.diskStorage({
  //配置路径,首先需要创建uploads/images文件夹
  destination: (req, file, cb) => {
    cb(null, './uploads/images');
  },
  //设置文件名
  filename: (req, file, cb) => {
    let extName = '.' + file.originalname.split('.').pop();
    let fileName = Date.now() + Math.floor(Math.random() * 10000);
    cb(null, fileName + extName);
  }
})
//应用上传设置，并实例上传对象
const upload = multer({
  storage: storage
})
//---------上传配置结束-----------------------------

//**************星号内部写API接口******************* */
//获取openid 小程序
router.get('/wxlogin', async (req, res) => {
  console.log(req.query)
  const {
    code
  } = req.query;
  console.log(code);
  const appID = "wxf266afeaa4fb0874"
  const AppSecret = "3c7f13079048155b54bd5cc76537be32"
  //访问微信服务器，需要使用request框架，打开新控制台 输入 npm install request --save下载
  const request = require('request')
  request({
    url: `https://api.weixin.qq.com/sns/jscode2session?appid=${appID}&secret=${AppSecret}&js_code=${code}&grant_type=authorization_code`
  }, (err, response, data) => {
    if (!err && response.statusCode == 200) {
      // console.log(typeof (data))
      res.send({
        status: 'ok',
        openid: JSON.parse(data).openid
      });
    } else {
      console.log(err);
      res.send({
        status: 'err',
        errMsg: err
      })
    }
  });
})

//小程序用户登录，判断用户是否存在，如不存在，则保存用户,如果存在，则读取用户信息并返回
router.post('/wxGetUserInfo', async (req, res) => {
  // console.log(req.body);
  try {
    const {
      userInfo
    } = req.body
    const result = await user.findOne({
      openid: userInfo.openid
    }).select('-_id')
    //console.log(result)
    if (result) {
      //返回数据库中的结果
      res.send({
        status: 'ok',
        value: result
      })
    } else {
      //保存用户
      user.create(userInfo).then((r) => {
        res.send({
          status: 'ok',
          value: userInfo
        })
      })
    }
  } catch (err) {
    console.log(err)
    res.send({
      status: 'err'
    })
  }
})

//头像图片上传
router.post('/uploadImg', upload.single('img'), (req, res) => {
  try {
    res.send(req.file);
  } catch (error) {
    res.send(error);
    console.log(error)
  }
})

//userRouter.js 小程序端 修改用户信息
router.post('/wxUpdateUserInfo', async (req, res) => {
  console.log(req.body)
  try {
    const {
      openid
    } = req.body
    const result = await user.findOneAndUpdate({
      openid
    }, req.body).select('-_id')
    res.send({
      status: 'success',
      result
    })
  } catch (error) {
    console.log(error)
    res.send({
      status: 'err'
    })
  }
})

//小程序端 申请成为接单员
router.post('/wxApplyOrder', async (req, res) => {
  try {
    // console.log(req.body)
    const {
      openid,
      personInfo
    } = req.body
    const result = await user.findOneAndUpdate({
      openid
    }, {
      personInfo
    })
    res.send('success')
  } catch (err) {
    console.log(err)
    res.send('fail')
  }
})

//小程序 读取用户申请接单信息
router.get('/wxGetUser', async (req, res) => {
  try {
    const {
      openid
    } = req.query
    const result = await user.findOne({
      openid
    }).select("personInfo")
    res.send({
      status: 'success',
      result
    })
  } catch (error) {
    res.send({
      status: 'fail'
    })
  }
})

//小程序 管理员读取所有用户接单申请
router.get('/wxGetAllApply', async (req, res) => {
  try {
    const {
      page,
      pageSizes
    } = req.query;
    const result = await user.find({
      personInfo: {
        $ne: null
      }
    }).select("personInfo").skip(page).limit(pageSizes).sort({
      "personInfo.applyTime": -1
    });
    res.send(result)
  } catch (error) {
    res.send(error)
  }
})

//小程序 读取接单申请的记录数
router.get('/wxApplyCount', async (req, res) => {
  try {
    const count = await user.countDocuments({
      personInfo: {
        $ne: null
      }
    });
    res.send({
      status: 'success',
      count
    })
  } catch (error) {
    res.send({
      status: 'error'
    })
  }
})

//小程序 审核接单申请
router.post('/wxApplyVerify', async (req, res) => {
  try {
    //console.log(req.body)
    const {
      _id,
      status
    } = req.body
    if (status === "通过审核") {
      await user.findByIdAndUpdate(_id, {
        canReceive: true,
        "personInfo.status": status
      })
    } else {
      await user.findByIdAndUpdate(_id, {
        "personInfo.status": status
      })
    }
    res.send('success')
  } catch (error) {
    console.log(error)
    res.send('fail')
  }
})

//************************************************* */
//导出路由
module.exports = router;